﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using LeonardoNews.Models;
using LeonardoNews.Data;

namespace LeonardoNews.Server.Repositories
{
    public class VotesRepository
    {
        private NewsContext context;

        public VotesRepository()
        {
            this.context = new NewsContext();
        }

        public IEnumerable<Vote> GetVotes()
        {
            var votes = context.Votes.Include(v => v.User).Include(v => v.Article);
            return votes.AsEnumerable();
        }

        public Vote GetVote(int id)
        {
            Vote vote = context.Votes.Include(v => v.User).Include(v => v.Article).FirstOrDefault(v => v.ID == id);
            return vote;
        }

        public void PutVote(Vote vote)
        {
            context.Entry(vote).State = EntityState.Modified;
            context.SaveChanges();
        }

        public void PostVote(Vote vote)
        {
            context.Votes.Add(vote);
            context.SaveChanges();
        }

        public Vote DeleteVote(int id)
        {
            Vote vote = context.Votes.Find(id);

            if (vote == null)
            {
                throw new NullReferenceException("Id don't exists");
            }

            context.Votes.Remove(vote);
            context.SaveChanges();
            return vote;
        }
    }
}